from django.db import models

import json
import pickle
import time

class Question(models.Model):
	author = models.CharField(max_length=64)
	description = models.TextField()
	last_update = models.DateTimeField('Last Update')
	return_type = models.CharField(max_length=32)
	signature = models.CharField(max_length=512)
	time_created = models.DateTimeField('Time Created')
	title = models.CharField(max_length=128)

	def toJSON(self):
		oJson = {'author': self.author,
			'description': self.description,
			'last_update': time.mktime(self.last_update.timetuple()),
			'return_type': self.return_type,
			'arg_list': pickle.loads(str(self.signature)),
			'time_created': time.mktime(self.time_created.timetuple()),
			'title': self.title,
			'q_id': self.id,
		}
		return oJson

	def __unicode__(self):
		return self.title

class Testcase(models.Model):
	answer = models.TextField(blank=True)
	answer_provided = models.BooleanField()
	author = models.CharField(max_length=64)
	data = models.TextField()
	last_update = models.DateTimeField('Last Update')
	question = models.ForeignKey(Question)

	def toJSON(self):
		oJson = {'answer': self.answer,
			'answer_provided': self.answer_provided,
			'author': self.author,
			'entry': pickle.loads(str(self.data)),
			't_id': self.id,
			'last_update': time.mktime(self.last_update.timetuple()),
			'question_id': self.question_id,
		}
		return oJson

	def __unicode__(self):
		return json.dumps(self.toJSON())

class Solution(models.Model):
	author = models.CharField(max_length=64, blank=True)
	lang = models.CharField(max_length=16)
	last_update = models.DateTimeField('Last Update')
	name = models.CharField(max_length=32)
	time_created = models.DateTimeField('Time Created')
	program = models.TextField()
	question = models.ForeignKey(Question)

	def toJSON(self):
		oJson = {'author': self.author,
			'sol_id': self.id,
			'author': self.author,
			'lang': self.lang,
			'last_update': time.mktime(self.last_update.timetuple()),
			'name': self.name,
			'time_created': time.mktime(self.time_created.timetuple()),
			'program': self.program,
			'question_id': self.question_id,
		}
		return oJson

	def updateFromJSON(self, oJson):
		self.lang = oJson['lang']
		self.last_update = oJson['last_update']
		self.name = oJson['name']
		self.program = oJson['program']

	def __unicode__(self):
		return json.dumps(self.toJSON())

